import random
from time import localtime

from requests import post, get

from date_util import get_birthday, get_love_days
from weather_util import get_weather
from word_util import get_caihongpi


def get_color():
    color_list = ["#" + "%06x" % random.randint(0, 0xFFFFFF) for _ in range(100)]
    return random.choice(color_list)


def get_access_token(app_id, app_secret):
    post_url = ("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}"
                .format(app_id, app_secret))
    return get(post_url).json()['access_token']


def send_message(to_user, user_info, access_token, template_id, chp_key, weather_key):
    note_ch = get_caihongpi(chp_key)

    location_id = user_info['location_id']
    location_name = user_info['location_name']
    weather, temp, wind_dir = get_weather(location_id, weather_key)

    today, week, love_days = get_love_days(user_info["love_date"])

    data = {
        "touser": to_user,
        "template_id": template_id,
        "url": "http://weixin.qq.com/download",
        "topcolor": "#FF0000",
        "data": {
            "date": {
                "value": "{} {}".format(today, week),
                "color": get_color()
            },
            "region": {
                "value": location_name,
                "color": get_color()
            },
            "weather": {
                "value": weather,
                "color": get_color()
            },
            "temp": {
                "value": temp,
                "color": get_color()
            },
            "wind_dir": {
                "value": wind_dir,
                "color": get_color()
            },
            "love_day": {
                "value": love_days,
                "color": get_color()
            },
            "note_ch": {
                "value": note_ch,
                "color": get_color()
            }
        }
    }

    # 获取距离下次生日的时间
    birth_day = get_birthday(user_info["birthday"], localtime().tm_year, today)
    if birth_day == 0:
        birthday_data = "今天是{}生日哦，生日快乐~".format(user_info["name"])
    else:
        birthday_data = "距离{}的生日还有{}天".format(user_info["name"], birth_day)
    data["data"]['birthday'] = {"value": birthday_data, "color": get_color()}

    response = post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={}".format(access_token),
                    json=data).json()

    if response["errcode"] == 0:
        print("推送消息成功：", user_info["name"])
    else:
        print("推送消息失败：", user_info["name"], response)
